﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using DBLayer;
using System.IO;

namespace EngineLayer.Common
{
    using EngineLayer.Properties;
    using EngineLayer.Model;

    public class FTPHandler : DBEntities , IFtp
    {
     //   private WebException Err;
        private FTPServer _ftp;
        private string ftpName;

        public FTPHandler(FTPServer ftp)
        {
            try
            {
                _ftp = ftp;//db.FTPServers.FirstOrDefault();
                ftpName = "ftp://" + ftp.HostName + "/" + EngineResources.UploadPath + "/";
            }
            catch
            { }
        }

#region Implement IFtp Interface
        
        public string GetFileData(string FileName)
        {
            Uri uri;
            string FileData = "";

            uri = new Uri(ftpName + FileName);

            try
            {
                FileData = GetFileFromServer(uri);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
             
            
            return FileData;
        }
    
        public IEnumerable<string> GetFileList()
        {
            List<string> results = new List<string>();
            FtpWebRequest request;
            FtpWebResponse response;
            Stream responseStream;
            StreamReader reader;


            request = createFTPConnection();
            request.Method = WebRequestMethods.Ftp.ListDirectory;

            response = (FtpWebResponse)request.GetResponse();
            responseStream = response.GetResponseStream();
            reader = new StreamReader(responseStream);

            while (!reader.EndOfStream)
                results.Add(reader.ReadLine());

            reader.Close();
            response.Close();

            return results;
        }

        public bool UploadFile(string FileName)
        {
            try
            {
                UploadSingleFile(FileName);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return true;
        }

#endregion
     
        private FtpWebRequest createFTPConnection(string FileName = "")
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpName + Path.GetFileName(FileName));
            request.Credentials = new NetworkCredential(_ftp.UserName, _ftp.Password);
            request.Timeout = 5000;
            return request;
        }
     
        private string GetFileFromServer(Uri serverUri)
        {
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                throw new Exception(EngineResources.InvalidURL);
            }

            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(_ftp.UserName, _ftp.Password);

            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] newFileData = request.DownloadData(serverUri.ToString());

            return ascii.GetString(newFileData);
        }

        private void UploadSingleFile(string FileName)
        {
            FtpWebRequest request;
            FileStream stream;
            Stream reqStream;

            request = createFTPConnection(Path.GetFileName(FileName));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;

            stream = File.OpenRead(FileName);
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();

            reqStream = request.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Flush();
            reqStream.Close(); 
        }
      
        public FTPServer FtpInfo
        {
            get
            {
                return _ftp;
            }
        }
    }
}
